package com.hualan.controller;

import com.hualan.util.R;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * 作者:烟火味的男孩儿
 * 描述:一条寻找bug的道路
 * 时间:2024/9/10
 */
@RestController
@RequestMapping("/upload")
public class upload {

    @PostMapping("/image")
    public R uploadImage(MultipartFile file) throws IOException {
        String path = "E:\\uploadImage\\";
        //获取照片原来的名称
        String originalFilename = file.getOriginalFilename();
        //截取文件名的后缀
        String ext = originalFilename.substring(originalFilename.lastIndexOf("."));
        //为了文件的唯一性问题，使用UUID的随机,创建新的名称
        String newFileName = UUID.randomUUID().toString() + ext;
        path += newFileName;
        file.transferTo(new File(path));
        return R.success(newFileName);
    }

    @GetMapping("/down")
    public void down(String filename, HttpServletResponse response) throws IOException {
        FileInputStream in = new FileInputStream("E:\\uploadImage\\"+filename);
        ServletOutputStream out = response.getOutputStream();
        byte[] b = new byte[1024];
        int i = in.read(b);
        while (i != -1) {
            out.write(b, 0, i);
            i = in.read(b);
        }
        out.close();
        in.close();
    }

}
